/**
 * Created by Administrator on 2018/1/27.
 */
let connection = require('../../bin/api');
let sqlName = require('../../config/sqlname');
let sql = require('../../db/BlogSQL');

exports.checkToken = function (req, res, next) {
    var token = false;
    if (req.headers.authorization && req.headers.authorization.indexOf('Bearer') === 0) {
        token = req.headers.authorization.replace('Bearer', '').trim();
    }

    if (!token) {
        token = req.headers.authorization || req.headers.token || req.query.token || req.body.token;
    }
    if (token) {
        connection.SelectData(sqlName.selectCheckToken, sql.token_select_check(req.query.token), function (err, result) {
            console.log("token时效" + result.tokenExpire);
            if (result != null) {
                if (new Date().getTime() < result.tokenExpire) {
                    req.params._id = result.userId;
                    next();
                }
                else {
                    return res.json({code: 11, message: "Token超时"});
                }
            } else {
                return res.json({code: 10, message: "Token已失效"});
            }
        }).catch(next);
    } else {
        return res.json({code: 10, message: "Token已失效"});
    }
}